<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="输入产品名称" />
      <el-select v-model="listQuery.tag" clearable style="width: 200px" class="filter-item" placeholder="选择产品标签" >
        <el-option v-for="(item,index) in tags" :key="index" :label="item.name" :value="item.value" />
        <el-option :label="'全部'" :value="''" />
      </el-select>
      <el-select v-model="listQuery.shelf" clearable style="width: 200px" class="filter-item" placeholder="选择产品状态" >
        <el-option v-for="(item,index) in shelfStatus" :key="index" :label="item.name" :value="item.value" />
        <el-option :label="'全部'" :value="''" />
      </el-select>
      <el-cascader :props="{label:'name', value:'id', children:'children', checkStrictly: true}" :options="categories" placeholder="请选择产品类目" clearable class="filter-item" filterable @change="chooseCategory" />
      <el-button v-permission="['product:list']" class="filter-item" type="primary" icon="el-icon-search" @click="search">查找</el-button>
      <el-button v-permission="['product:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="toAddProduct">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中..." border fit highlight-current-row>
      <el-table-column type="expand" label="产品规格" width="80">
        <template slot-scope="props">
          <el-table v-loading="listLoading" :data="props.row.skus" size="small" border>
            <el-table-column type="index" width="50"/>
            <el-table-column align="center" label="产品规格" prop="title" />
            <el-table-column align="center" label="产品库存" prop="stock" />
            <el-table-column align="center" label="原价" prop="originalPrice" />
            <el-table-column align="center" label="现价" prop="price" />
            <el-table-column align="center" label="VIP价格" prop="vipPrice" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" prop="id" width="80"/>
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <el-link type="primary" @click="loadProductTxtAndAttr(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" property="url" label="图片" width="80">
        <template slot-scope="scope">
          <el-image :src="scope.row.url+'_40_40'" @click="loadProductImg(scope.row.id)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品类目" prop="categoryName" width="100"/>
      <el-table-column align="center" label="邮费模板" prop="freightTemplateName" width="100"/>
      <el-table-column align="center" label="销量" width="80">
        <template slot-scope="scope">
          {{ scope.row.sales }}{{ scope.row.unit }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售状态" prop="onShelf" width="80">
        <template slot-scope="scope">
          <el-switch v-permission="['product:editOnShelf']" v-model="scope.row.onShelf" active-color="#13ce66" inactive-color="#dcdfe6" @change="changeShelf(scope.row.id,$event)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" width="80">
        <template slot-scope="scope">
          <input v-permission="['product:sort']" :value="scope.row.seq" class="el-input__inner" maxlength="10" @blur="sortProduct($event,scope.row)">
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['product:detail']" type="primary" size="mini" @click="toEditProduct(scope.row)">编辑</el-button>
          <el-button v-permission="['product:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="initList"/>

    <el-drawer :visible.sync="productTxtDialogVisible" :append-to-body="true" :title="productTxt.title" size="50%">
      <el-tabs :stretch="true" v-model="activeTab" type="card">
        <el-tab-pane label="产品属性" name="productAttrTab">
          <el-table :data="productAttrs" :stripe="true" border>
            <el-table-column prop="name" label="名称" align="center"/>
            <el-table-column prop="data" label="值" align="center"/>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="产品详情" name="productTxtTab">
          <div style="text-align:center" v-html="productTxt.content"/>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <el-image-viewer v-if="productImgVisible" :on-close="closeImageViewer" :url-list="productImgs" />
  </div>
</template>

<script>
import { ProductService } from '@/api/ProductService'
import { CategoryService } from '@/api/ProductService'
import { DictionaryService } from '@/api/CommonService'
import Pagination from '@/components/Pagination'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import Notify from '@/utils/notify'

export default {
  name: 'ProductList',
  components: { Pagination, ElImageViewer },
  data() {
    return {
      list: [], total: 0, tags: [],
      productTxtDialogVisible: false, productImgVisible: false,
      productTxt: { title: '', content: '' }, productImgs: [], productAttrs: [], categories: [],
      listLoading: true, activeTab: 'productAttrTab',
      shelfStatus: [{ value: false, name: '下架' }, { value: true, name: '正常' }],
      listQuery: { pageNo: 1, pageSize: 20, name: undefined, shelf: undefined, categoryId: undefined, tag: undefined },
      selectedIds: []
    }
  },
  created() {
    this.initList()
    this.loadCategory()
    this.loadProductTag()
  },
  methods: {
    initList() {
      this.listLoading = true
      ProductService.listProduct(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    search() {
      this.listQuery.pageNo = 1
      this.initList()
    },
    loadProductTag() {
      DictionaryService.listDictionaryByType('product_tag').then(res => {
        this.tags = res
      })
    },
    loadProductTxtAndAttr(row) {
      ProductService.getProductTxt(row.id).then(result => {
        this.productTxt.title = row.name
        this.productTxt.content = result.remark
        this.productTxtDialogVisible = true
      })
      ProductService.getProductAttr(row.id).then(result => {
        this.productAttrs = result
      })
    },
    loadProductImg(productId) {
      ProductService.getProductImg(productId).then(result => {
        this.productImgs = result
        if (this.productImgs && this.productImgs.length > 0) {
          this.productImgVisible = true
        }
      })
    },
    closeImageViewer() {
      this.productImgVisible = false
      this.productImgs = []
    },
    toAddProduct() {
      this.$router.push({ path: '/product/add' })
    },
    toEditProduct(row) {
      this.$router.push({ path: '/product/detail', query: { productId: row.id }})
    },
    handleDelete(row) {
      this.$confirm('您确认要删除该产品吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        ProductService.deleteProduct(row.id).then(() => {
          Notify.success(this, '删除成功!')
          this.initList()
        })
      }).catch(() => {
        return false
      })
    },
    loadCategory() {
      CategoryService.loadCategoryTree().then(result => {
        this.categories = result
      })
    },
    chooseCategory(e) {
      const tag = e[e.length - 1]
      this.listQuery.categoryId = tag
    },
    changeShelf(productId, isOnShelf) {
      ProductService.editShelf(productId, isOnShelf).then(() => {
        Notify.success(this, '操作成功!')
        this.initList()
      })
    },
    sortProduct(event, row) {
      const newVal = event.target.value
      const oldVal = row.seq
      if (parseInt(oldVal) !== parseInt(newVal)) {
        ProductService.sortProduct({ productId: row.id, seq: newVal }).then(() => {
          this.initList()
        })
      }
    }
  }
}
</script>
<style>
  .el-drawer__body { overflow-x: auto; }
</style>
